/*
 SGHighScoresViewController.m
 Date Created: February 17, 2010
 
 Author: Karol Krizka <kkrizka@gmail.com>
 
 Copyright (C) 2010 Green-Power
 
 URL: http://code.google.com/p/green-power
 
 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 3 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 $Id$
 */

#import "SGHighScoresViewController.h"

@implementation SGHighScoresViewController

@synthesize managedObjectContext;
@synthesize scoreAreaView;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
  [super viewDidLoad];
  [self setTitle:@"High Scores"];
	
  [self setupHighScoreLabels];
  
}

- (void)clearHighScoreLabels {
  NSArray *subviews=[[self scoreAreaView] subviews];
  for(UIView *subview in subviews) {
    [subview removeFromSuperview];
  }
}

- (void)setupHighScoreLabels {
  NSFetchRequest *fetchRequest=[[NSFetchRequest alloc] init];
  [fetchRequest setFetchLimit:10];
  
  NSEntityDescription *officialScoreEntity=[NSEntityDescription entityForName:@"OfficialScore" inManagedObjectContext:[self managedObjectContext]];
  NSEntityDescription *scoreEntity=[NSEntityDescription entityForName:@"Score" inManagedObjectContext:[self managedObjectContext]];
  [fetchRequest setEntity:scoreEntity];
  
  NSSortDescriptor *sortDescriptor=[[NSSortDescriptor alloc] initWithKey:@"score" ascending:NO];
  NSArray *sortDescriptors=[[NSArray alloc] initWithObjects:sortDescriptor,nil];
  [fetchRequest setSortDescriptors:sortDescriptors];
  [sortDescriptors release];
  [sortDescriptor release];
  
  NSError *error;
  NSMutableArray *mutableFetchResults=[[[self managedObjectContext] executeFetchRequest:fetchRequest error:&error] mutableCopy];
  if(mutableFetchResults) {
    // Calculate the rectangle dimensions for the entry labels
    CGRect scoreAreaBounds=[[self scoreAreaView] bounds];
    CGRect nameLabelBounds=CGRectMake(0,0,200,20);
    CGRect scoreLabelBounds=CGRectMake(scoreAreaBounds.size.width-50,0,50,20);
    
    int i=0;
    for(NSManagedObject *s in mutableFetchResults) {
      NSNumber *score=[s valueForKey:@"score"];
      
      nameLabelBounds.origin.y=i*25;
      UILabel *nameLabel=[[UILabel alloc] initWithFrame:nameLabelBounds];
      [nameLabel setBackgroundColor:UIColor.clearColor];
      
      scoreLabelBounds.origin.y=i*25;
      UILabel *scoreLabel=[[UILabel alloc] initWithFrame:scoreLabelBounds];
      [scoreLabel setText:[score stringValue]];
      [scoreLabel setTextAlignment:UITextAlignmentRight];
      [scoreLabel setBackgroundColor:UIColor.clearColor];
      
      NSEntityDescription *entityDescription=[s entity];
      NSString *profileName;
      if([entityDescription isKindOfEntity:officialScoreEntity]) {
        profileName=[s valueForKey:@"profileName"];
        [nameLabel setTextColor:[UIColor blueColor]];
        [scoreLabel setTextColor:[UIColor blueColor]];
      } else {
        // This is a score associated with a profile, therefore use the owner
        // relationship to get the profile name.
        NSManagedObject *owner=(NSManagedObject*)[s valueForKey:@"owner"];
        profileName=[owner valueForKey:@"profileName"];
      }
      [nameLabel setText:profileName];
      
      [[self scoreAreaView] addSubview:nameLabel];
      [[self scoreAreaView] addSubview:scoreLabel];
      
      [nameLabel release];
      [scoreLabel release];
      i++;
    }
  }
  
  [mutableFetchResults release];
  [fetchRequest release];
}

- (IBAction)handleClearHighScores:(id)sender {
  UIAlertView *confirmAlert=[[UIAlertView alloc] initWithTitle:@"Confirm" 
                                                       message:@"Are you certain that you want to clear your high scores?"
                                                      delegate:self
                                             cancelButtonTitle:@"No"
                                             otherButtonTitles:@"Yes",nil];
  [confirmAlert show];
  [confirmAlert release];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
  // Button index 0 is "No"
  if(buttonIndex==1) { // Button index 1 is "Yes"
    [self clearHighScores];
  }
}

- (void)clearHighScores {
  NSFetchRequest *fetchRequest=[[NSFetchRequest alloc] init];
  [fetchRequest setFetchLimit:0];

  NSEntityDescription *officialScoreEntity=[NSEntityDescription entityForName:@"OfficialScore" 
                                                       inManagedObjectContext:[self managedObjectContext]];
  NSEntityDescription *scoreEntity=[NSEntityDescription entityForName:@"Score" 
                                               inManagedObjectContext:[self managedObjectContext]];
  [fetchRequest setEntity:scoreEntity];
  
  NSError *error;
  NSMutableArray *results=[[[self managedObjectContext] executeFetchRequest:fetchRequest
                                                                      error:&error] mutableCopy];
  if( results ) {
    for(NSManagedObject *scoreObj in results) {
      NSEntityDescription *entity=[scoreObj entity];
      if(![entity isKindOfEntity:officialScoreEntity]) {
        // Do not clear official scores!
        [[self managedObjectContext] deleteObject:scoreObj];
      }
    }
  }
	
  if(![[self managedObjectContext] save:&error]) {
    NSLog(@"Error saving high scores..");
  }
  
  // Refresh the display!
  [self clearHighScoreLabels];
  [self setupHighScoreLabels];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  [[self navigationController] setNavigationBarHidden:NO animated:YES];
}


@end
